import java.sql.*;

public class FixAdminPassword {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://db.test1.wcsbapp.com:3306/ChainUp?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8";
            
            try (Connection conn = DriverManager.getConnection(url, "admin", "0YvoGUzwhumnf2KGQvjN")) {
                System.out.println("=== 使用RuoYi默认密码哈希修复admin用户 ===");
                
                // 删除现有admin用户的所有关联
                System.out.println("清理现有数据...");
                
                String[] cleanupSqls = {
                    "DELETE FROM sys_user_role WHERE user_id = 1",
                    "DELETE FROM sys_user_post WHERE user_id = 1", 
                    "DELETE FROM sys_user WHERE user_name = 'admin'"
                };
                
                for (String sql : cleanupSqls) {
                    try (PreparedStatement ps = conn.prepareStatement(sql)) {
                        ps.executeUpdate();
                    }
                }
                
                // 确保基础角色存在
                String roleCheckSql = "SELECT role_id FROM sys_role WHERE role_id = 1";
                try (PreparedStatement ps = conn.prepareStatement(roleCheckSql)) {
                    ResultSet rs = ps.executeQuery();
                    if (!rs.next()) {
                        // 创建超级管理员角色
                        String createRoleSql = "INSERT INTO sys_role (role_id, role_name, role_key, role_sort, data_scope, menu_check_strictly, dept_check_strictly, status, del_flag, create_by, create_time, remark) VALUES (1, '超级管理员', 'admin', 1, '1', 1, 1, '0', '0', 'admin', NOW(), '超级管理员')";
                        try (PreparedStatement rolePs = conn.prepareStatement(createRoleSql)) {
                            rolePs.executeUpdate();
                            System.out.println("✓ 超级管理员角色已创建");
                        }
                    }
                }
                
                // 确保部门存在
                String deptCheckSql = "SELECT dept_id FROM sys_dept WHERE dept_id = 103";
                try (PreparedStatement ps = conn.prepareStatement(deptCheckSql)) {
                    ResultSet rs = ps.executeQuery();
                    if (!rs.next()) {
                        String[] deptSqls = {
                            "INSERT INTO sys_dept (dept_id, parent_id, ancestors, dept_name, order_num, leader, phone, email, status, del_flag, create_by, create_time) VALUES (100, 0, '0', 'ChainUp科技', 0, '管理员', '15888888888', 'admin@chainup.com', '0', '0', 'admin', NOW())",
                            "INSERT INTO sys_dept (dept_id, parent_id, ancestors, dept_name, order_num, leader, phone, email, status, del_flag, create_by, create_time) VALUES (101, 100, '0,100', '巡检中心', 1, '管理员', '15888888888', 'admin@chainup.com', '0', '0', 'admin', NOW())",
                            "INSERT INTO sys_dept (dept_id, parent_id, ancestors, dept_name, order_num, leader, phone, email, status, del_flag, create_by, create_time) VALUES (103, 101, '0,100,101', 'API监控组', 1, '管理员', '15888888888', 'admin@chainup.com', '0', '0', 'admin', NOW())"
                        };
                        for (String sql : deptSqls) {
                            try (PreparedStatement deptPs = conn.prepareStatement(sql)) {
                                deptPs.executeUpdate();
                            }
                        }
                        System.out.println("✓ 部门结构已创建");
                    }
                }
                
                // 使用RuoYi框架的默认密码哈希 (对应密码是admin123)
                String ruoyiDefaultHash = "$2a$10$7JB720yubVSOfvam/u3aYeBPF.JRw6KgWWj5YX1.WGK5OZCeIGu8W";
                
                // 创建完整的admin用户
                String insertUserSql = """
                    INSERT INTO sys_user (
                        user_id, dept_id, user_name, nick_name, user_type, email, 
                        phonenumber, sex, avatar, password, status, del_flag, 
                        login_ip, login_date, create_by, create_time, update_by, 
                        update_time, remark
                    ) VALUES (
                        1, 103, 'admin', '管理员', '00', 'admin@chainup.com',
                        '15888888888', '1', '', ?, '0', '0',
                        '127.0.0.1', now(), 'admin', now(), '',
                        now(), '管理员'
                    )
                """;
                
                try (PreparedStatement ps = conn.prepareStatement(insertUserSql)) {
                    ps.setString(1, ruoyiDefaultHash);
                    ps.executeUpdate();
                    System.out.println("✓ admin用户创建成功");
                    System.out.println("  密码哈希: " + ruoyiDefaultHash.substring(0, 30) + "...");
                }
                
                // 分配超级管理员角色
                String userRoleSql = "INSERT INTO sys_user_role (user_id, role_id) VALUES (1, 1)";
                try (PreparedStatement ps = conn.prepareStatement(userRoleSql)) {
                    ps.executeUpdate();
                    System.out.println("✓ 用户角色关联成功");
                }
                
                // 确保岗位存在并关联
                String postCheckSql = "SELECT post_id FROM sys_post WHERE post_id = 1";
                try (PreparedStatement ps = conn.prepareStatement(postCheckSql)) {
                    ResultSet rs = ps.executeQuery();
                    if (!rs.next()) {
                        String createPostSql = "INSERT INTO sys_post (post_id, post_code, post_name, post_sort, status, create_by, create_time, remark) VALUES (1, 'ceo', '董事长', 1, '0', 'admin', NOW(), '')";
                        try (PreparedStatement postPs = conn.prepareStatement(createPostSql)) {
                            postPs.executeUpdate();
                            System.out.println("✓ 岗位已创建");
                        }
                    }
                    
                    String userPostSql = "INSERT INTO sys_user_post (user_id, post_id) VALUES (1, 1)";
                    try (PreparedStatement postPs = conn.prepareStatement(userPostSql)) {
                        postPs.executeUpdate();
                        System.out.println("✓ 用户岗位关联成功");
                    } catch (Exception e) {
                        // 可能已存在，忽略
                    }
                }
                
                // 验证用户是否创建成功
                String verifySql = "SELECT user_id, user_name, nick_name, status, dept_id FROM sys_user WHERE user_name = 'admin'";
                try (PreparedStatement ps = conn.prepareStatement(verifySql)) {
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        System.out.println("\n=== 验证结果 ===");
                        System.out.println("用户ID: " + rs.getInt("user_id"));
                        System.out.println("用户名: " + rs.getString("user_name"));
                        System.out.println("昵称: " + rs.getString("nick_name"));
                        System.out.println("状态: " + ("0".equals(rs.getString("status")) ? "正常" : "停用"));
                        System.out.println("部门ID: " + rs.getInt("dept_id"));
                    }
                }
                
                System.out.println("\n=== 登录信息 ===");
                System.out.println("地址: http://localhost:1024/");
                System.out.println("用户名: admin");
                System.out.println("密码: admin123");
                System.out.println("注意: Redis缓存已清除，可以立即尝试登录");
                System.out.println("================");
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}